<template>
  <div class="df-form-item">
    <!--判断插槽-->
    <template v-if="props.schema?.slot">
      <slot
        :name="props.schema?.slot"
        :model="props.formModel"
        :field="props.field"
        :value="props.formModel[props.field]"
      ></slot>
    </template>

    <!--NCheckbox-->
    <template v-else-if="props.schema?.component === 'NCheckbox'">
      <n-checkbox-group
        :value="props.formModel[props.field]"
        @update:value="(val) => updateFormModelFn({ [props.field]: val })"
      >
        <n-space>
          <n-checkbox
            v-for="item in props.schema?.componentProps.options"
            :key="item.value"
            :value="item.value"
            :label="item.label"
            :disabled="!!item.disabled"
          />
        </n-space>
      </n-checkbox-group>
    </template>

    <!--NRadioGroup-->
    <template v-else-if="props.schema?.component === 'NRadioGroup'">
      <n-radio-group
        :value="props.formModel[props.field]"
        v-bind="getComponentProps(props.schema)"
        @update:value="(val) => updateFormModelFn({ [props.field]: val })"
      >
        <n-space>
          <n-radio
            v-for="item in props.schema?.componentProps.options"
            :key="item.value"
            :value="item.value"
          >
            {{ item.label }}
          </n-radio>
        </n-space>
      </n-radio-group>
    </template>
    <!-- DFSelectSearch -->
    <template v-else-if="props.schema?.component === 'SelectSearch'">
      <DFSelectSearch
        :placeholder="$t('common.form.plSelect')"
        width="100%"
        :formValue="props.formModel[props.field] ? props.formModel[props.field] : null"
        :disabled="props.schema?.componentProps.disabled"
        remote
        filterable
        :resetMenuOnOptionsChange="false"
        v-bind="props.schema?.componentProps"
        :isFilterList="componentBind.isFilterList"
        :isEditTable="props.isEditTable"
        :filterKey="componentBind.filterKey"
        :filterList="props.schema?.filterList"
        :table="props.table"
        @update:value="
          (val, obj) => {
            dfSelectSearchUpdateValueFn(val,obj)
          }
        "
      />
    </template>

    <template v-else-if="props.schema?.component === 'UploadImage'">
      <DFUploadImage
        :file-url="props.formModel[props.field]"
        :file-name="props.formModel[props.field + 'Name']"
        :showNotice="false"
        :fileType="props.schema?.componentProps?.fileType || ['bmp', 'jpg', 'png']"
        :maxSize="props.schema?.componentProps?.maxSize || 10"
        :max="props.schema?.componentProps?.max || 10"
        @response-img="
          (obj) => {
            updateFormModelFn({ [props.field]: obj.fileUrl, [props.field + 'Name']: obj.fileName });

            props.schema?.componentProps.onUpdateValue &&
              props.schema?.componentProps.onUpdateValue(obj, updateFormModelFn);
          }
        "
      />
    </template>

    <template v-else-if="props.schema?.component === 'NColorPicker'">
      <NColorPicker
        v-bind="componentBind"
        :value="props.formModel[props.field]"
        :on-update:value="
          (val, obj) => {
            compontUpdateValueFn(val,obj)

          }
        "
      />
    </template>

    <!--动态渲染表单组件-->
    <component
      v-else-if="props.schema?.component"
      :maxlength="250"
      v-bind="componentBind"
      @keyup="handleKeyUp"
      @blur="() => handleBlur(props.schema)"
      :is="componentBind.component"
      :value="props.formModel[props.field]"
      @clear="
        (val, obj) => {
          compoentClearFn(val,obj);

        }
      "
      @update:value="
        (val, obj) => {
          compontUpdateValueFn(val,obj)

        }
      "
      :class="{ isFull: props.schema.isFull != false && props.getProps.isFull }"
    />
    <!--组件后面的内容-->

    <template v-if="props.schema?.suffix">
      <slot
        :name="props.schema?.suffix"
        :model="props.formModel"
        :field="props.field"
        :value="props.formModel[props.field]"
      ></slot>
    </template>
  </div>
</template>

<script lang="ts" setup name="DFFormItem">
  import DFSelectSearch from '@/components/DFSelectSearch/index.vue';
  import { createPlaceholderMessage } from './helper';
  import { cloneDeep } from 'lodash-es';

  type Props = {
    schema?: any;
    formModel?: any;
    getProps?: any;
    field?: any;
    isEditTable?: boolean;
    table?: any;
    isSearchForm?: boolean;
  };

  const props: any = withDefaults(defineProps<Props>(), {
    schema: () => ({}),
    formModel: () => ({}),
    getProps: () => ({}),
    field: () => '',
    isEditTable: () => false,
    table: () => ({}),
  });

  const emit = defineEmits(['handleSubmitFn', 'setFieldsValueFn']);

  const componentBind = computed(() => getComponentProps(props.schema));

  function updateFormModelFn(obj) {
    emit('setFieldsValueFn', obj);
  }

  function getComponentProps(schema: any = {}) {
    const compProps = schema.componentProps ?? {};
    const component = schema.component;

    if (component === 'NSelect' && !compProps['render-label']) {
      compProps['render-label'] = (row) => {
        const label = compProps?.labelField || 'label';

        return h('span', {
          innerText: row[label],
          title: row[label],
        });
      };
    }

    return {
      clearable: true,
      placeholder: props.collcheck ? '' : createPlaceholderMessage(unref(component)),
      ...compProps,
      ...{
        disabled:
          compProps.disabled && typeof compProps.disabled === 'function'
            ? compProps.disabled(props.formModel)
            : !!compProps.disabled,
      },
      component: typeof component === 'function' ? component(props.formModel) : component,
    };
  }

  // 回车
  function handleKeyUp(e: any) {
    if (e.keyCode == '13' && props.isSearchForm) {
      emit('handleSubmitFn');
    }
  }

  // 失去焦点默认去除前后空格
  function handleBlur(schema: any) {
    const { component, componentProps, field } = schema;
    const { onBlur } = componentProps || {};
    if (component === 'NInput') {
      onBlur && onBlur();
      let obj = cloneDeep(props.formModel);
      obj[field] = obj[field] && obj[field].trim();

      updateFormModelFn(obj);
      // setFieldsValue(obj);
    }
  }

  // function handleChangeSelectFn(val, props, _row) {
  //   // const { listValue } = props;
  //   // console.log(val);
  //   console.log(props);
  //   // Object.values(props).map((e: any) => {
  //   //   updateFormModelFn({ [e]: val?.[e] || null });
  //   // });
// }

  const dfSelectSearchUpdateValueFn = (val, obj) => {
    if(!(val instanceof Event)){
      updateFormModelFn({ [props.field]: val });

      props.schema?.componentProps.onUpdateValue &&
        props.schema?.componentProps.onUpdateValue(
          val,
          obj,
          updateFormModelFn,
          props.formModel
        );
      }
  }

  const compoentClearFn = (val, obj) => {
    if(!(val instanceof Event)){
      updateFormModelFn({ [props.field]: val });
      componentBind.value.onClear &&
        componentBind.value.onClear(val, obj, updateFormModelFn, props.formModel);
    }
  }

  const compontUpdateValueFn = (val, obj) => {
    if(!(val instanceof Event)){
      updateFormModelFn({ [props.field]: val });
      componentBind.value.onUpdateValue &&
        componentBind.value.onUpdateValue(val, obj, updateFormModelFn, props.formModel);
    }
  }
</script>

<style lang="less">
  .df-form-item {
    width: 100%;
    padding: 2px;
  }
</style>
